<?php

namespace App\Http\Controllers\Admin;
use App\Model\Demand;
use App\Model\Stock;
use App\User;
use App\Model\MaterialList;
use App\Model\Goods;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class StockController extends Controller
{
    /**
     * 列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function list(Request $request)
    {
        $company_id = $request->input("company_id",0);
        return view('admin/stock/list')->with('company_id',$company_id);
    }

    /**
     * 公共列表
     * @param $request
     * @return array
     */
    public function pub($request){
        $company_id = $request->input("company_id",0);
        $query= Stock::select(DB::raw('*,SUM(warehouse)'))->where('company_id',$company_id)->groupBy('material_id');
        return $query;
    }

    /**
     * 数据操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function data(Request $request)
    {
        $query = $this->pub($request);
        $res=$query->paginate($request->get('limit',15))->toArray();
        $goods= Goods::get()->toArray();
        $goods_arr = array_column($goods,'name','id');
        $materialList= MaterialList::get()->toArray();
        $material_arr = array_column($materialList,'name','id');
        foreach ($res['data'] as $key=>$val){
            $g_name = isset($goods_arr[$val['goods_id']]) ? $goods_arr[$val['goods_id']] : '';
            $m_name = isset($material_arr[$val['material_id']]) ? $material_arr[$val['material_id']] : '';
            $res['data'][$key]['goods_name'] = $g_name;
            $res['data'][$key]['material_name'] = $m_name;
        }
        $data = [
            'code' => 0,
            'msg'   => '请求成功',
            'count' => $res['total'],
            'data'  => $res['data']
        ];
        return response()->json($data);
    }

}
